﻿
using AutoMapper;
using IdGen;
using Newtonsoft.Json;
using Ross.EntityFramework;
using Ross.EntityFramework.Model;
using Ross.Service.Dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Diagnostics;

namespace Ross.Service
{
    public class TargetService : BaseService, IDisposable
    {
        private TranDbContext dbContext;
        public IRepository<Targets, int> repository;
        public IRepository<Users, int> userresp;

        public TargetService(string nameOrConnectionString)
        {
            dbContext = new TranDbContext(nameOrConnectionString);
            repository = new Repository<Targets, int>(dbContext);
            userresp = new Repository<Users, int>(dbContext);
            
        }

        public ResultDto<bool> NewInsert(Dto.NewZongBiao input)
        {
            var result = new ResultDto<bool>();
            try
            {
                var model = Mapper.Map<Targets>(input);
                model.StartingTime = Convert.ToDateTime(input.Timespan[0]);
                model.PlannedCompletionTime = Convert.ToDateTime(input.Timespan[1]);
                int pdepth = -1;
                if (input.ParentTargetID > 0)
                {
                    pdepth = repository.Get(input.ParentTargetID).Depth;
                }
                model.Depth = pdepth + 1;
                repository.Insert(model);
                result.status = 200;
                result.datas = true;
            }
            catch (Exception ex)
            {
                result.message = ex.Message;
                result.status = 500;
                result.datas = false;
            }

            return result;
        }

        public ResultDto<List<Dto.TargetOutput>> NewChaXunZongBiao2(string keywords = "", string departId = "", string status = "", string timespan = "")
        {
            //按年份查询根节点，0，1，N
            //子节点为空时，child=null
            //部门为空时，默认查询所有授权部门
            //部门的深度为3
            //var result = new ResultDto<List<Dto.NewZongBiao>>();
            List<Dto.TargetOutput> trees = new List<TargetOutput>();
            List<Dto.TargetOutput> zhanlue = new List<TargetOutput>();
            ResultDto<List<Dto.TargetOutput>> result = new ResultDto<List<Dto.TargetOutput>>();
            var listsAll = repository.GetAllList();
            if (!string.IsNullOrEmpty(username))
            {
                var user = userresp.GetAllList(o => o.UserName == username || o.EmpID == username).FirstOrDefault();
                string[] adepts = user.AuthorizedDepartment.Split(',');
                Expression<Func<Targets, bool>> expression = o => o.Depth == 3 && o.TargetName == year.ToString();
                if (!string.IsNullOrEmpty(keywords))
                    expression = expression.ExpressionAnd(t => t.TargetName.Contains(keywords));
                if (!string.IsNullOrEmpty(departId))
                    expression = expression.ExpressionAnd(t => t.Department == departId);
                else
                    expression = expression.ExpressionAnd(t => adepts.Contains(t.Department));
                if (!string.IsNullOrEmpty(status))
                    expression = expression.ExpressionAnd(t => t.ApprovalStatus == status);
                if (!string.IsNullOrEmpty(timespan))
                {
                    DateTime starttime = Convert.ToDateTime(timespan.Split(',')[0]);
                    DateTime endtime = Convert.ToDateTime(timespan.Split(',')[1]);
                    expression = expression.ExpressionAnd(t => t.StartingTime >= starttime && t.StartingTime <= endtime);
                }
                var lists = repository.GetAllList(expression).ToList();
                foreach (var item in lists)
                {
                    TargetOutput obj = new TargetOutput();
                    obj = Mapper.Map<Dto.TargetOutput>(item);
                    obj.children = GetTargetsTree(listsAll, item.ID);
                    if (obj.children.Count == 0)
                        obj.children = null;
                    trees.Add(obj);
                }
            }
            result.total = trees.Count;
            result.datas = trees;

            var n = repository.GetAllList();


            return result;

        }
        public ResultDto<List<Dto.TargetOutput>> NewChaXunBuMen()
        {

            var result = new ResultDto<List<Dto.TargetOutput>>();
            Expression<Func<Targets, bool>> expression = o => o.Depth <= 3;
            var lists = repository.GetAllList(expression);
            var trees = GetTargetsTree(lists, -1);
            //var model = Mapper.Map<NewZongBiao>(trees);

            var tree = trees.Where(u => u.TargetName == year.ToString()).ToList();

            if (tree.Count == 1)
            {
                result.status = 200;
                result.datas = tree.First().children;
                return result;
            }
            else if (tree.Count == 0)
            {
                result.message = $"无{year}年度记录";
                result.status = 500;
                result.datas = null;
                return result;
            }

            throw new Exception($"根节点错误，存在多个{year}年度节点");


        }

        public ResultDto<bool> NewUpdate(Dto.NewZongBiao input)
        {

            ResultDto<bool> result = new ResultDto<bool>();
            try
            {

                var bumen = repository.Get(input.ID);

                //if (bumen.ApprovalStatus != "未审核")
                //{
                //    result.message = $"{bumen.ApprovalStatus}状态下不允许修改";
                //    result.status = 500;
                //    result.datas = false;
                //    return result;
                //}

                bumen.Department = input.Department;
                bumen.TargetName = input.TargetName;
                bumen.TargetDescription = input.TargetDescription;
                bumen.AssessmentCriteria = input.AssessmentCriteria;
                bumen.AssessmentMethod = input.AssessmentMethod;
                bumen.AccountingMethod = input.AccountingMethod;
                bumen.Statistician = input.Statistician;
                bumen.ResourceSupport = input.ResourceSupport;
                bumen.Budget1 = input.Budget1;
                bumen.Budget2 = input.Budget2;
                bumen.Budget3 = input.Budget3;
                bumen.CostCategory1 = input.CostCategory1;
                bumen.CostCategory2 = input.CostCategory2;
                bumen.CostCategory3 = input.CostCategory3;
                bumen.Responsible = input.Responsible;
                bumen.email = input.email;


                bumen.ApprovalStatus = input.ApprovalStatus;
                //bumen.Version = input.Version;
                bumen.ReviseTime = DateTime.Now;

                bumen.StartingTime = Convert.ToDateTime(input.Timespan[0]);
                bumen.PlannedCompletionTime = Convert.ToDateTime(input.Timespan[1]);
                bumen.TargetCenter = input.TargetCenter;
                bumen.TargetTeam = input.TargetTeam;
                bumen.CompletionCriteria = input.CompletionCriteria;


                repository.Update(bumen);


                result.status = 200;
                result.datas = true;
            }
            catch (Exception ex)
            {
                result.message = ex.Message;
                result.status = 500;
                result.datas = false;
            }
            return result;
        } //end

        public ResultDto<bool> NewApproveTarget(int id, string status)
        {
            ResultDto<bool> result = new ResultDto<bool>();

            var t = repository.Get(id);

            if (status == "审核中")
            {
                t.ApprovalStatus = status;
                t.ApprovalTime = DateTime.Now;
                repository.Update(t);
                result.status = 200;
                result.datas = true;
                return result;
            }
            if (status == "未审核")
            {
                //未审核更新此节点
                //然后更新所有子节点
                var lists = repository.GetAllList();
                t.ApprovalStatus = status;
                t.ApprovalTime = DateTime.Now;


                var zijiedians = GetTargetsTree(lists, id);

                if (!ChangeApproveTarget(zijiedians))
                {
                    result.status = 500;
                    result.datas = false;
                    return result;
                }

                repository.Update(t);
                result.status = 200;
                result.datas = true;
                return result;
                
            }

            //当节点深度为3时，


            t.ApprovalStatus = status;
            t.ApprovalTime = DateTime.Now;
            repository.Update(t);
            result.status = 200;
            result.datas = true;
            return result;

            ////提交审核中时，上级必须为已审核

            //var p = repository.Get(t.ParentTargetID).ApprovalStatus;
            //if (p == "已审核")
            //{
            //    t.ApprovalStatus = status;
            //    t.ApprovalTime = DateTime.Now;
            //    repository.Update(t);
            //    result.status = 200;
            //    result.datas = true;
            //    return result;
            //}

            //result.message = "上层目标未审核通过";
            //result.status = 500;
            //result.datas = false;
            //return result;
        }

        public ResultDto<bool> NewDelete(int id)
        {
            ResultDto<bool> result = new ResultDto<bool>();
            try
            {
                var obj = repository.Get(id);

                //if (obj.ApprovalStatus != "未审核")
                //{
                //    result.message = $"{obj.ApprovalStatus}状态下不允许删除";
                //    result.status = 500;
                //    result.datas = false;
                //    return result;
                //}

                if (repository.GetAllList(o => o.ParentTargetID == id).Count != 0)
                {
                    result.message = $"子目标存在的情况下不允许删除";
                    result.status = 500;
                    result.datas = false;
                    return result;
                }
                repository.Delete(id);

                result.status = 200;
                result.datas = true;
            }
            catch (Exception ex)
            {
                result.message = ex.Message;
                result.status = 500;
                result.datas = false;
            }
            return result;
        }

        public  ResultDto<bool> InsertGen(Dto.TargetsOutput input)
        {
            ResultDto<bool> result = new ResultDto<bool>();
            //前端创建，提供ID:-1时，生成跟节点；不提供时，生成子节点
                var targetsgongsi = new Targets()
                {
                    ParentTargetID = -1,
                    Classification = input.Classification,
                    TargetName = input.TargetName,
                    Department = input.Department,
                    ApprovalStatus = "已审核",
                    Version = input.Version,
                    CreationTime = DateTime.Now,
                    Lock = false,
                    Approver = "001",
                    StartingTime=Convert.ToDateTime(input.Timespan[0]),
                    PlannedCompletionTime= Convert.ToDateTime(input.Timespan[1]),
                    TargetDescription=input .TargetDescription,
                    Depth=0,
                };
                var id = repository.InsertAndGetId(targetsgongsi);
                input.ParentTargetID = id;

            Targets targetbumen = new Targets()
            {
                ParentTargetID = input.ParentTargetID,
                Classification = input.Classification,
                TargetName = input.DepTargetName,
                AssessmentCriteria = input.AssessmentCriteria,
                Department = input.Department,
                ApprovalStatus = "未审核",
                Version = input.Version,
                CreationTime = DateTime.Now,
                Lock = false,
                Approver = "001",
                StartingTime = Convert.ToDateTime(input.Timespan[0]),
                PlannedCompletionTime = Convert.ToDateTime(input.Timespan[1]),
                TargetDescription = input.TargetDescription,
                Depth=1,
            };
            repository.Insert(targetbumen);
            result.status = 200;
            result.datas = true;
            return result;
        }

        public ResultDto<bool> InsertZi(Dto.TargetsOutput input)
        {
            ResultDto<bool> result = new ResultDto<bool>();
            
            Targets targetbumen = new Targets()
            {
                ParentTargetID = input.ParentTargetID,
                Classification = input.Classification,
                TargetName = input.DepTargetName,
                AssessmentCriteria = input.AssessmentCriteria,
                Department = input.Department,
                ApprovalStatus = "未审核",
                Version = input.Version,
                CreationTime = DateTime.Now,
                Lock = false,
                Approver = "001",
                StartingTime = Convert.ToDateTime(input.Timespan[0]),
                PlannedCompletionTime = Convert.ToDateTime(input.Timespan[1]),
                TargetDescription = input.TargetDescription,
                Depth=1,
            };
            repository.Insert(targetbumen);
            result.status = 200;
            result.datas = true;
            return result;
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <returns></returns>
        public ResultDto<List<Dto.TargetOutput>> GetAllList(string keywords = "", string departId = "", string status = "",string version = "")
        {
            ResultDto<List<Dto.TargetOutput>> result = new ResultDto<List<Dto.TargetOutput>>();
            Expression<Func<Targets, bool>> expression = o => o.ID > 0;
            if (!string.IsNullOrEmpty(keywords))
                expression = expression.ExpressionAnd(t => t.TargetName.Contains(keywords));
            if (!string.IsNullOrEmpty(departId))
                expression = expression.ExpressionAnd(t => t.Department == departId);
            if (!string.IsNullOrEmpty(status))
                expression = expression.ExpressionAnd(t => t.ApprovalStatus == status);
            if (!string.IsNullOrEmpty(version))
                expression = expression.ExpressionAnd(t => t.Version == version);

            if (!string.IsNullOrEmpty(username))
            {
                var obj = userresp.GetAllList(o => o.UserName == username).FirstOrDefault();
                if (obj != null)
                {
                    expression = expression.ExpressionAnd(t => obj.AuthorizedDepartment.Contains(t.Department));
                }
            }
            var lists = repository.GetAllList(expression);
            result.datas = Mapper.Map<List<Dto.TargetOutput>>(lists);
            result.total = lists.Count;
            return result;
        }

        public ResultDto<bool> NewXiuBian(BuMenBiaoOutput input)
        {
            ResultDto<bool> result = new ResultDto<bool>();

            //已审核状态下才可修编
            if (input.ApprovalStatus != "已审核")
            {
                result.message = $"已审核状态下才可修编";
                result.status = 500;
                result.datas = false;
                return result;
            }

            //点修编提交整颗年度树
            //移除未审核

            var all = repository.GetAllList().ToList();

            var historyrepositorys = new Repository<History, int>(dbContext);
            foreach (var t in all)
            {
                History history = new History()
                {
                    SourceID = t.ID,
                    Classification = t.Classification,
                    Department = t.Department,
                    TargetName = t.TargetName,
                    TargetDescription = t.TargetDescription,
                    AssessmentCriteria = t.AssessmentCriteria,
                    AssessmentMethod = t.AssessmentMethod,
                    AccountingMethod = t.AccountingMethod,
                    Statistician = t.Statistician,
                    ResourceSupport = t.ResourceSupport,
                    Responsible = t.Responsible,
                    PlanningDocumentURL = t.PlanningDocumentURL,
                    Lock = t.Lock,
                    TargetState = t.TargetState,
                    ParentTargetID = t.ParentTargetID,
                    CreationTime = t.CreationTime,
                    StartingTime = t.StartingTime,
                    PlannedCompletionTime = t.PlannedCompletionTime,
                    ActualCompletionTime = t.ActualCompletionTime,
                    ReviseTime = t.ReviseTime,
                    Approver = t.Approver,
                    ApprovalStatus = t.ApprovalStatus,
                    ApprovalTime = t.ApprovalTime,
                    Version = input.Version,//拿表单的
                    Depth = t.Depth,
                    Budget1 = t.Budget1,
                    Budget2 = t.Budget2,
                    Budget3 = t.Budget3,
                    CostCategory1 = t.CostCategory1,
                    CostCategory2 = t.CostCategory2,
                    CostCategory3 = t.CostCategory3,
                };
                historyrepositorys.Insert(history);
            }


            //再更新当前表
            try
            {
                var bumen = repository.Get(input.ID);

                bumen.Classification = input.Classification;
                bumen.Department = input.Department;
                bumen.TargetName = input.TargetName;
                bumen.TargetDescription = input.TargetDescription;
                bumen.AssessmentCriteria = input.AssessmentCriteria;
                bumen.AssessmentMethod = input.AssessmentMethod;
                bumen.AccountingMethod = input.AccountingMethod;
                bumen.Statistician = input.Statistician;
                bumen.ResourceSupport = input.ResourceSupport;
                bumen.Budget1 = input.Budget1;
                bumen.Budget2 = input.Budget2;
                bumen.Budget3 = input.Budget3;
                bumen.CostCategory1 = input.CostCategory1;
                bumen.CostCategory2 = input.CostCategory2;
                bumen.CostCategory3 = input.CostCategory3;
                bumen.Responsible = input.Responsible;
                bumen.ApprovalStatus = "未审核";
                bumen.Version = input.Version;
                bumen.ReviseTime = DateTime.Now;

                bumen.StartingTime = input.StartingTime;
                bumen.PlannedCompletionTime = input.PlannedCompletionTime;

                repository.Update(bumen);


                result.status = 200;
                result.datas = true;
            }
            catch (Exception ex)
            {
                result.message = ex.Message;
                result.status = 500;
                result.datas = false;
            }

            //同时子节点刷新未审核
            var lists = repository.GetAllList();

            var zijiedians = GetTargetsTree(lists, input.ID);
            //刷新子节点
            if (!ChangeApproveTarget(zijiedians))
            {
                result.status = 500;
                result.datas = false;
                return result;
            }

            //如果当前深度为战略目标，修编结束后，修改发布状态为false

            var end = repository.Get(input.ID);
            if (end.Depth == 2)
            {
                var d3 = repository.GetAllList(o => o.Depth == 3).Where(u => u.ParentTargetID == input.ID).ToList();


                //子集修改
                foreach (var i in d3)
                {
                    i.Lock = false;
                    repository.Update(i);
                }
            }

            return result;

        }

        /// <summary>
        /// 修编战略
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ResultDto<bool> XiuBianZhanlue(ZhanLueInput input)
        {
            
            ResultDto<bool> result = new ResultDto<bool>();
            try
            {
                //先将记录插入历史表
                InsertHistory();
                //在进行修改
                var zhanlue = repository.Get(input.ID);
                zhanlue.TargetName = input.TargetName;
                zhanlue.ReviseTime = DateTime.Now;
                zhanlue.ApprovalStatus = "未审核";
                repository.Update(zhanlue);
                //将子节点的状态进行更新
                var lists = repository.GetAllList();
                var zijiedians = GetTargetsTree(lists, input.ID);
                //刷新子节点
                result = UpdateZijiedian(result, input.ID);
                result.status = 200;
                result.datas = true;
            }
            catch (Exception e)
            {
                result.status = 200;
                result.datas = false;
                result.message = e.Message;
                //throw;
            }
            return result;
        }
        /// <summary>
        /// 修编部门
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ResultDto<bool> XiuBianBumen(BuMenInput input)
        {
            ResultDto<bool> result = new ResultDto<bool>();
            
            try
            {
                //先将记录插入历史表
                InsertHistory();
                //在进行修改
                var bumen = repository.Get(input.ID);
                bumen.TargetName = input.TargetName;
                bumen.Department = input.Department;
                bumen.ReviseTime = DateTime.Now;
                bumen.ApprovalStatus = "未审核";
                bumen.AssessmentCriteria = input.AssessmentCriteria;
                bumen.TargetCenter = input.TargetCenter;
                bumen.TargetTeam = input.TargetTeam;

                repository.Update(bumen);
                //将子节点的状态进行更新
                var lists = repository.GetAllList();

                var zijiedians = GetTargetsTree(lists, input.ID);
                //刷新子节点
                result = UpdateZijiedian(result, input.ID);
                result.status = 200;
                result.datas = true;
                
            }
            catch (Exception e)
            {
                result.status = 200;
                result.datas = false;
                result.message = e.Message;
            }
            return result;
        }

        public ResultDto<List<Dto.TargetOutput>> GetTreeList(string keywords = "", string departId = "", string status = "", string version = "")
        {
            ResultDto<List<Dto.TargetOutput>> result = new ResultDto<List<Dto.TargetOutput>>();
            var lists = repository.GetAllList();
            var resp = GetTargetsTree(lists);
            result.total = resp.Count;
            result.datas = resp;
            return result;
        }

        private List<Dto.TargetOutput> GetTargetsTree(List<Targets> datas, int parentid = 0)
        {
            List<Dto.TargetOutput> result = new List<Dto.TargetOutput>();
            var lists = datas.Where(o => o.ParentTargetID == parentid).ToList();
            foreach(var item in lists)
            {
                Dto.TargetOutput obj = new Dto.TargetOutput();
                obj = Mapper.Map<Dto.TargetOutput>(item);
                var childrens = datas.Where(o => o.ParentTargetID == item.ID).ToList();
                if(childrens.Count>0)
                {
                    obj.children = GetTargetsTree(datas, item.ID);
                }
                result.Add(obj);
            }
            return result;
        }

        private List<Dto.TargetInput> GetTargets(List<Dto.TargetOutput> datas)
        {
            List<Dto.TargetInput> result = new List<Dto.TargetInput>();
            foreach (var item in datas)
            {
                Dto.TargetInput obj = new Dto.TargetInput();
                obj = Mapper.Map<Dto.TargetInput>(item);
                if (item.children!=null)
                {
                    GetTargets(item.children);
                }
                result.Add(obj);
            }
            return result;
        }

        public ResultDto<List<Dto.TargetsOutput>> ChaXunZongBiao()
        {
            var result = new ResultDto<List<Dto.TargetsOutput>>();
            //查公司级的未审核，审核中
            Expression<Func<Targets, bool>> expGongSiJi = t => t.ParentTargetID == -1 ;
            //查询公司级未审核的
            var gongSiJi = repository.GetAllList(expGongSiJi);
            var zongbiao = repository.GetAllList();
            var childrens = new List<Dto.TargetsOutput>();
            //其对应下级
            foreach (var i in gongSiJi)
            {
                var buMenJi = zongbiao.Where(t => t.ParentTargetID == i.ID).ToList();

                //其子节点集合
                foreach (var j in buMenJi)
                {
                    var childeren = new Dto.TargetsOutput()
                    {
                        ID = j.ID,
                        Department = j.Department,
                        TargetName = i.TargetName,
                        DepTargetName=j.TargetName,
                        Classification = j.Classification,
                        AssessmentCriteria = j.AssessmentCriteria,
                        ParentTargetID = j.ParentTargetID,
                        ApprovalStatus = j.ApprovalStatus,
                    };
                    childrens.Add(childeren);
                }
            }
            result.datas = childrens;
            return result;
        } //end

        public ResultDto<bool> Delete(int id)
        {
            ResultDto<bool> result = new ResultDto<bool>();
            try
            {
                var obj = repository.Get(id);

                if(obj.ApprovalStatus!="未审核")
                {
                    result.message = $"{obj.ApprovalStatus}状态下不允许删除";
                    result.status = 500;
                    result.datas = false;
                    return result;
                }

                //查询其父节点
                //查询父节点所有子节点一次
                //遍历所有子节点ID
                //删除所有ID
             
                var fujiedian = repository.Get(obj.ParentTargetID);
                var zijiedians = repository.GetAllList(t => t.ParentTargetID == fujiedian.ID);
                var ids=zijiedians.Select(o => o.ID).ToList();

                //任何一个子节点的子节点存在，也不能删除
                var x= repository.GetAllList().Where(o => id==o.ParentTargetID).ToList();

                if (x.Count!=0)
                {
                    result.message = $"子目标存在的情况下不允许删除";
                    result.status = 500;
                    result.datas = false;
                    return result;
                }
                if(ids.Count==1)
                {
                    repository.Delete(id);
                    repository.Delete(fujiedian.ID);
                }

                repository.Delete(id);
                TongBuShanChu(id);
                result.status = 200;
                result.datas = true;
            }
            catch (Exception ex)
            {
                result.message = ex.Message;
                result.status = 500;
                result.datas = false;
            }
            return result;
        }

        public ResultDto<bool> Deletebumen(int id)
        {
            ResultDto<bool> result = new ResultDto<bool>();
            try
            {
                var obj = repository.Get(id);

                if (obj.Depth < 2)
                {
                    result.message = "无权删除此节点";
                    result.status = 500;
                    result.datas = false;
                    return result;
                }

                if (obj.ApprovalStatus != "未审核")
                {
                    result.message = $"{obj.ApprovalStatus}状态下不允许删除";
                    result.status = 500;
                    result.datas = false;
                    return result;
                }

                if(repository.GetAllList(o=>o.ParentTargetID==id).Count!=0)
                {
                    result.message = $"子目标存在的情况下不允许删除";
                    result.status = 500;
                    result.datas = false;
                    return result;
                }
                //查询所有子节点父节点为此节点
                //添加此节点
                //删除所有ID
                var zijiedians = repository.GetAllList(t => t.ParentTargetID == id);
                var ids = zijiedians.Select(o => o.ID).ToList();
                ids.Add(id);

                foreach (var i in ids)
                {
                    repository.Delete(i);
                    TongBuShanChu(i);
                }

                result.status = 200;
                result.datas = true;
            }
            catch (Exception ex)
            {
                result.message = ex.Message;
                result.status = 500;
                result.datas = false;
            }
            return result;
        }

        /// <summary>
        /// 审核
        /// </summary>
        /// <param name="id"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public ResultDto<bool> ApproveTarget(int id, string status)
        {
            ResultDto<bool> result = new ResultDto<bool>();

            var t = repository.Get(id);
            if (t.ParentTargetID > 0)
            {
                var p = repository.Get(t.ParentTargetID);
                if (p != null && p.ApprovalStatus != "已审核")
                {
                    result.message = "上层目标未审核";
                    result.status = 500;
                    result.datas = false;
                    return result;
                }
            }

            t.ApprovalStatus = status;
            t.ApprovalTime = DateTime.Now;
            repository.Update(t);
            result.status = 200;
            result.datas = true;

            return result;
        }

        /// <summary>
        /// 发布
        /// </summary>
        /// <param name="id"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public ResultDto<bool> FaBu(int id, bool status)
        {
            ResultDto<bool> result = new ResultDto<bool>();

            //发布后将12层状态改为已审
            var t = repository.Get(id);
            var p = repository.Get(t.ParentTargetID);
            p.Lock = true;
            p.ApprovalStatus = "已审核";
            t.ApprovalStatus = "已审核";
            repository.Update(p);

            t.Lock = status;
            repository.Update(t);
            result.status = 200;
            result.datas = true;
            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="outputs"></param>
        /// <returns></returns>
        public bool ChangeApproveTarget(List<TargetOutput> outputs)
        {
            try
            {
                foreach (var i in outputs)
                {
                    //修改每个节点
                     var t= repository.Get(i.ID);
                    t.ApprovalStatus = "未审核";
                    repository.Update(t);
                    if (i.children != null)
                    {
                        ChangeApproveTarget(i.children);
                    }
                }
            }
            catch
            {
                return false;
            }
            return true;
        }
        public ResultDto<bool> Update(Dto.TargetsOutput input)
        {

            ResultDto<bool> result = new ResultDto<bool>();
            try
            {
                var gognsi = repository.Get(input.ParentTargetID);
                var bumen = repository.Get(input.ID);
                

                if (bumen.ApprovalStatus!="未审核")
                {
                    result.message = $"{bumen.ApprovalStatus}无法修改";
                    result.status = 500;
                    result.datas = false;
                    return result;
                }

                gognsi.ID = input.ParentTargetID;
                gognsi.Classification = input.Classification;
                gognsi.TargetName = input.TargetName;
                gognsi.ApprovalStatus = input.ApprovalStatus;
                gognsi.Version = input.Version;
                gognsi.ReviseTime = DateTime.Now;
                gognsi.TargetDescription = input.TargetDescription;
                gognsi.StartingTime = Convert.ToDateTime(input.Timespan[0]);
                gognsi.PlannedCompletionTime = Convert.ToDateTime(input.Timespan[1]);


                bumen.Classification = input.Classification;
                bumen.TargetName = input.DepTargetName;
                bumen.AssessmentCriteria = input.AssessmentCriteria;
                bumen.Department = input.Department;
                bumen.ApprovalStatus = input.ApprovalStatus;
                bumen.Version = input.Version;
                bumen.ReviseTime = DateTime.Now;
                bumen.TargetDescription = input.TargetDescription;
                bumen.StartingTime = Convert.ToDateTime(input.Timespan[0]);
                bumen.PlannedCompletionTime = Convert.ToDateTime(input.Timespan[1]);
        
                repository.Update(bumen);
                repository.Update(gognsi);

                result.status = 200;
                result.datas = true;
            }
            catch (Exception ex)
            {
                result.message = ex.Message;
                result.status = 500;
                result.datas = false;
            }
            return result;
        } //end

        public ResultDto<Targets> GetTarget(int id)
        {
            ResultDto<Targets> result = new ResultDto<Targets>();
            Expression<Func<Targets, bool>> expression = o => o.ID == id;
            var t = repository.GetAllList(expression);
            if (t.Count == 0)
            {
                result.message = "无效ID";
                result.status = 500;
                result.datas = null;
                return result;
            }
            result.status = 200;
            result.datas = t.First();
            return result;
        }

        /// <summary>
        /// 表锁定条件
        /// </summary>
        /// <param name="exp"></param>
        /// <returns></returns>
        public bool LockTable(string exp)
        {
            if (exp == "审核中" || exp == "已审核")
                return true;
            return false;
        }

        public ResultDto<string> GetDepartment()
        {
            ResultDto<string> result = new ResultDto<string>();
            List<string> dep = new List<string>();
            string obj = "";

            //根据id 查询授权部门
            if (string.IsNullOrEmpty(username))
            {
                result.message = "用户名不能为空";
                result.status = 500;
                return result;
            }
            obj = userresp.GetAllList(o => o.UserName == username).FirstOrDefault().AuthorizedDepartment;

            result.status = 200;
            result.datas = obj;
            return result;
        }

        public List<Depart> GetDeptAsync()
        {
            ResultDto<List<Service.Dto.Depart>> result = new ResultDto<List<Service.Dto.Depart>>();

            //后续联系杨凯雨拿到管理员账号才可以拉取全部门名称
            string url = BudgetServer + "/api/Department/GetAllList?userId=000022";
            var t = Task.Run(async () =>
            {
                string response = await RemoteGet(url);
                result = JsonConvert.DeserializeObject<ResultDto<List<Service.Dto.Depart>>>(response);
            });
            t.Wait();
            return result.datas;
        }

        //public List<Depart> GetDeptAsync()
        //{
        //    ResultDto<List<Service.Dto.Depart>> result = new ResultDto<List<Service.Dto.Depart>>();

        //    //后续联系杨凯雨拿到管理员账号才可以拉取全部门名称
        //    string url = BudgetServer + "/api/Department/GetAllList?userId=000022";
        //    var t = Task.Run(async () =>
        //    {
        //        string response = await RemoteGet(url);
        //        result = JsonConvert.DeserializeObject<ResultDto<List<Service.Dto.Depart>>>(response);
        //    });
        //    t.Wait();
        //    return result.datas;
        //}

        public async Task<List<Service.Dto.ExpenseCate>> GetCateAsync()
        {
            ResultDto<List<Service.Dto.ExpenseCate>> result = new ResultDto<List<Service.Dto.ExpenseCate>>();
            string url = BudgetServer + "/api/Expense/GetAllList";
            string response = await RemoteGet(url);
            result = JsonConvert.DeserializeObject<ResultDto<List<Service.Dto.ExpenseCate>>>(response);
            var t = result.datas;
            return t;
        }

        /// <summary>
        /// 部门表插入
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ResultDto<bool> Insert(Dto.BuMenBiaoOutput input)
        {
            ResultDto<bool> result = new ResultDto<bool>();
            var pDepth = repository.Get(input.ParentTargetID).Depth;

            if(pDepth>2)
            {
                //深度为3不可再添加
                result.message = "不可再添加子目标";
                result.status = 500;
                result.datas = false;
                return result;
            }

            Targets targetbumen = new Targets()
            {
                ParentTargetID = input.ParentTargetID,
                Classification = input.Classification,
                Department = input.Department,
                TargetName = input.TargetName,
                TargetDescription = input.TargetDescription,
                AssessmentCriteria = input.AssessmentCriteria,
                AssessmentMethod = input.AssessmentMethod,
                AccountingMethod = input.AccountingMethod,
                Statistician = input.Statistician,
                Responsible = input.Responsible,
                ApprovalStatus = "未审核",
                Version = input.Version,
                CreationTime = DateTime.Now,
                Lock = false,
                StartingTime = Convert.ToDateTime(input.Timespan[0]),
                PlannedCompletionTime = Convert.ToDateTime(input.Timespan[1]),
                Budget1 = input.Budget1,
                Budget2 = input.Budget2,
                Budget3 = input.Budget3,
                CostCategory1 = input.CostCategory1,
                CostCategory2 = input.CostCategory2,
                CostCategory3 = input.CostCategory3,
                ResourceSupport = input.ResourceSupport,
                Depth = pDepth + 1,
            };
            repository.Insert(targetbumen);
            result.status = 200;
            result.datas = true;
            return result;
        }

        /// <summary>
        /// 部门表更新
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ResultDto<bool> Update(Dto.NewZongBiao input)
        {

            ResultDto<bool> result = new ResultDto<bool>();
            try
            {

                var bumen = repository.Get(input.ID);

                if (bumen.ApprovalStatus != "未审核")
                {
                    result.message = $"{bumen.ApprovalStatus}状态下不允许修改";
                    result.status = 500;
                    result.datas = false;
                    return result;
                }

                bumen.Department = input.Department;
                bumen.TargetName = input.TargetName;
                bumen.TargetDescription = input.TargetDescription;
                bumen.AssessmentCriteria = input.AssessmentCriteria;
                bumen.AssessmentMethod = input.AssessmentMethod;
                bumen.AccountingMethod = input.AccountingMethod;
                bumen.Statistician = input.Statistician;
                bumen.ResourceSupport = input.ResourceSupport;
                bumen.Budget1 = input.Budget1;
                bumen.Budget2 = input.Budget2;
                bumen.Budget3 = input.Budget3;
                bumen.CostCategory1 = input.CostCategory1;
                bumen.CostCategory2 = input.CostCategory2;
                bumen.CostCategory3 = input.CostCategory3;
                bumen.Responsible = input.Responsible;

                
                bumen.ApprovalStatus = input.ApprovalStatus;
                //bumen.Version = input.Version;
                bumen.ReviseTime = DateTime.Now;
                
                bumen.StartingTime = Convert.ToDateTime(input.Timespan[0]);
                bumen.PlannedCompletionTime = Convert.ToDateTime(input.Timespan[1]);

                repository.Update(bumen);
         

                result.status = 200;
                result.datas = true;
            }
            catch (Exception ex)
            {
                result.message = ex.Message;
                result.status = 500;
                result.datas = false;
            }
            return result;
        } //end

        public ResultDto<List<Targets>> GetResourceTarget()
        {
            ResultDto<List<Targets>> result = new ResultDto<List<Targets>>();
            var shouquans = GetShouQuan().datas.Split(',');
            var resources = repository.GetAllList(o=>o.ApprovalStatus=="已审核");
            var t = resources.Where(o => shouquans.Contains(o.ResourceSupport)).ToList();
            result.status = 200;
            result.datas = t;
            return result;
        }

        /// <summary>
        /// 根据内存中的用户名获取到用户的整体信息（此项不包含密码）
        /// </summary>
        /// <returns></returns>
        public ResultDto<Dto.oUser> Get()
        {
            ResultDto<Dto.oUser> result = new ResultDto<Dto.oUser>();
            var repositorys = new Repository<Users, int>(dbContext);
            try
            {
                if (oPrincipal != null)
                {
                    var obj = repositorys.GetAllList(o => o.UserName == username||o.EmpID==username).FirstOrDefault();
                    if (obj != null)
                    {
                        result.status = 200;
                        result.datas = Mapper.Map<Dto.oUser>(obj);
                    }
                    else
                    {
                        result.message = "user is not exist";
                        result.status = 500;
                    }
                }
                else
                {
                    result.message = "Unable to access unauthorized app";
                    result.status = 500;
                }
            }
            catch (Exception e)
            {
                result.message = e.Message;
                result.status = 500;
            }
            return result;
        }

        /// <summary>
        /// 获得授权部门
        /// </summary>
        /// <returns></returns>
        public ResultDto<string> GetShouQuan()
        {
            ResultDto<string> result = new ResultDto<string>();
            var shouquans = Get().datas.AuthorizedDepartment;
            result.status = 200;
            result.datas = shouquans;
            return result;
        }

        public ResultDto<bool> GaiTargetState(int id, string status)
        {
            ResultDto<bool> result = new ResultDto<bool>();

            var t = repository.Get(id);
            t.TargetState = status;
            if (status == "已完成")
                t.ActualCompletionTime = DateTime.Now;
            else
                t.ActualCompletionTime = Convert.ToDateTime(null);
            repository.Update(t);
            result.status = 200;
            result.datas = true;
            return result;
        }

        /// <summary>
        /// 部门
        /// </summary>
        /// <param name="buMenBiaoOutput"></param>
        /// <returns></returns>
        public ResultDto<bool> XiuBian(BuMenBiaoOutput input)
        {
            ResultDto<bool> result = new ResultDto<bool>();

            //已审核状态下才可修编
            if (input.ApprovalStatus != "已审核")
            {
                result.message = $"已审核状态下才可修编";
                result.status = 500;
                result.datas = false;
                return result;
            }

            //先插入历史表
            InsertHistory();


            //再更新当前表
            try
            {
                var bumen = repository.Get(input.ID);

                bumen.Classification = input.Classification;
                bumen.Department = input.Department;
                bumen.TargetName = input.TargetName;
                bumen.TargetDescription = input.TargetDescription;
                bumen.AssessmentCriteria = input.AssessmentCriteria;
                bumen.AssessmentMethod = input.AssessmentMethod;
                bumen.AccountingMethod = input.AccountingMethod;
                bumen.Statistician = input.Statistician;
                bumen.ResourceSupport = input.ResourceSupport;
                bumen.Budget1 = input.Budget1;
                bumen.Budget2 = input.Budget2;
                bumen.Budget3 = input.Budget3;
                bumen.CostCategory1 = input.CostCategory1;
                bumen.CostCategory2 = input.CostCategory2;
                bumen.CostCategory3 = input.CostCategory3;
                bumen.Responsible = input.Responsible;
                bumen.ApprovalStatus = "未审核";
                bumen.Version = input.Version;
                bumen.ReviseTime = DateTime.Now;

                bumen.StartingTime = Convert.ToDateTime(input.Timespan[0]);
                bumen.PlannedCompletionTime = Convert.ToDateTime(input.Timespan[1]);
                bumen.email = input.email;
                bumen.TargetCenter = input.TargetCenter;
                bumen.TargetTeam = input.TargetTeam;
                
                repository.Update(bumen);

                result.status = 200;
                result.datas = true;
            }
            catch (Exception ex)
            {
                result.message = ex.Message;
                result.status = 500;
                result.datas = false;
            }
            UpdateZijiedian(result, input.ID);
            return result;
            
        }

        /// <summary>
        /// 将现有的记录转入历史
        /// </summary>
        private void InsertHistory()
        {
            //先插入历史表
            var alltargets = repository.GetAllList();
            var targets = alltargets.Where(o => o.Depth == 0 && o.StartingTime.Year == year).ToList();
            var all = new List<Targets>();
            

            all = GetTargetsData(targets[0],all, alltargets);
            all.Add(targets[0]);
            var xiubianhao = GetLiuShuiHao();
            var historyrepositorys = new Repository<History, int>(dbContext);
            var historys = new List<History>();
            foreach (var t in all)
            {
                History history = Mapper.Map<History>(t);
                history.Version = xiubianhao;
                history.SourceID = t.ID;
                historys.Add(history);
            }
            historyrepositorys.BulkInsert(historys);
        }

        private ResultDto<bool> UpdateZijiedian(ResultDto<bool> result, int id)
        {
            //同时子节点刷新未审核
            var lists = repository.GetAllList();

            var zijiedians = GetTargetsTree(lists, id);
            //刷新子节点
            if (!ChangeApproveTarget(zijiedians))
            {
                result.status = 500;
                result.datas = false;
                return result;
            }

            var end = repository.Get(id);
            end.Lock = false;
            repository.Update(end);
            if (end.Depth == 2)
            {
                var d3 = repository.GetAllList(o => o.Depth == 3).Where(u => u.ParentTargetID == id).ToList();
                //子集修改
                foreach (var i in d3)
                {
                    i.Lock = false;
                    repository.Update(i);
                }
            }
            return result;
        }

        /// <summary>
        /// 返回登录年份所有的数据
        /// </summary>
        /// <returns></returns>
        List<Targets> GetTargetsData(Targets targets, List<Targets> list,List<Targets> alltargets)
        {
            
            var t = alltargets.Where(o => o.ParentTargetID == targets.ID).ToList();
            if (t.Count > 0)
            {
                foreach (var item in t)
                {
                    list.Add(item);
                    GetTargetsData(item, list, alltargets);
                }

            }
            return list;
        }

        public ResultDto<List<History>> ShowVersion(int id)
        {
            var result = new ResultDto<List<History>>();
            var repositoryhistory = new Repository<History, int>(dbContext);
            //查询历史记录
            var t = repositoryhistory.GetAllList(o=>o.SourceID==id).OrderByDescending(o=>o.ID).ToList();
            
            result.datas = t;
            result.status = 200;
            return result;
        }

        /// <summary>
        ///同步删除历史版本
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool TongBuShanChu(int id)
        {
            var repository = new Repository<History, int>(dbContext);
            var delids = repository.GetAllList(o => o.SourceID == id);

            try
            {
                foreach (var i in delids)
                {
                    repository.Delete(i);
                }
            }
            catch
            {
                return false;
            }

            return true;
        }

         //向下查
        private List<NewZongBiao>  NewGetTargetsTree(List<NewZongBiao> datas,List<NewZongBiao> nodes)
        {
            //遍历每个集合
            foreach(var i in nodes)
            {
                //他的子节点
                var lists = datas.Where(u => u.ParentTargetID == i.ID).ToList();

                //加入子节点
                i.children = lists;
                NewGetTargetsTree(datas, i.children);
            }
            return nodes;
        }

        public ResultDto<List <NewZongBiao>> NewTree()
        {
            var nodes =repository.GetAllList(i=>i.ID==1);

            var result = new ResultDto<List<NewZongBiao>>();

            var t = NewGetTargetsTree(Mapper.Map<List<NewZongBiao>>(repository.GetAllList()), Mapper.Map<List<NewZongBiao>>(nodes));
            result.datas = t;
            return result;
        }

        public ResultDto<bool> InsertLiuShui()
        {
            var result = new ResultDto<bool>();

            var t= GetLiuShuiHao();
            
            result.status = 200;
            result.datas = true;
            return result;

        }
      
        public string GetLiuShuiHao()
        {
            //每次从表里查询年月日,没查到创建一个
            //查到时查找此年月日下最大的流水号
            var time = DateTime.Now.ToString("yyyyMMdd");
            var repository = new Repository<Sequence,int>(dbContext);
            var t = repository.GetAllList(o => o.Time == time);
     
            if (t.Count == 0)
            {
                repository.Insert(new Sequence() { Time = time, SeqNo = "001" });
                return time + "001";
            }
            //返回最大的流水号
            var result= t.Where(o=>o.Time==time).OrderByDescending(u=>u.SeqNo).First();

            var seq = Convert.ToInt32(result.SeqNo)+1;
            repository.Insert(new Sequence() { Time = time, SeqNo = seq.ToString("000")});
            return time+ seq.ToString().PadLeft(3, '0');
        }

        public ResultDto<bool> ZhanLueInsert(ZhanLueInput input)
        {
            var result = new ResultDto<bool>();
            try
            {
                var model = Mapper.Map<Targets>(input);
                var pdepth = repository.Get(input.ParentTargetID).Depth;
                model.Depth = pdepth + 1;
                repository.Insert(model);
                result.status = 200;
                result.datas = true;
            }
            catch (Exception ex)
            {
                result.message = ex.Message;
                result.status = 500;
                result.datas = false;
            }

            return result;
        }

        public ResultDto<bool> BuMenInsert(BuMenInput input)
        {
            var result = new ResultDto<bool>();


            try
            {
                var model = Mapper.Map<Targets>(input);
                var pdepth = repository.Get(input.ParentTargetID).Depth;
                model.Depth = pdepth + 1;
                model.Department = input.Department;
                repository.Insert(model);
                result.status = 200;
                result.datas = true;
            }
            catch (Exception ex)
            {
                result.message = ex.Message;
                result.status = 500;
                result.datas = false;
            }
            //foreach(var i in input.Departments)
            //{

            //}


            return result;
        }

        public ResultDto<bool> ZhanLueUpdate(ZhanLueInput input)
        {

            ResultDto<bool> result = new ResultDto<bool>();

            try
            {
                var zhanlue = repository.Get(input.ID);
                zhanlue.TargetName = input.TargetName;
                zhanlue.ReviseTime = DateTime.Now;
                repository.Update(zhanlue);

                result.status = 200;
                result.datas = true;
            }
            catch (Exception ex)
            {
                result.message = ex.Message;
                result.status = 500;
                result.datas = false;
            }

            return result;

        }

        public ResultDto<bool> BuMenUpdate(BuMenInput input)
        {

            ResultDto<bool> result = new ResultDto<bool>();

            try
            {
                var bumen = repository.Get(input.ID);
                bumen.Department = input.Department;
                bumen.TargetName = input.TargetName;
                bumen.AssessmentCriteria = input.AssessmentCriteria;
                bumen.ReviseTime = DateTime.Now;
                bumen.TargetTeam = input.TargetTeam;
                bumen.TargetCenter = input.TargetCenter;
                repository.Update(bumen);

                result.status = 200;
                result.datas = true;
            }
            catch (Exception ex)
            {
                result.message = ex.Message;
                result.status = 500;
                result.datas = false;
            }

            return result;

        }

        public ResultDto<List<ShenHeOutput>> ChaXunShenHeTemp()
        {
            var result = new ResultDto<List<ShenHeOutput>>();

            //查询计划  深度=3 审核中
            var jihua1 = repository.GetAllList(o => o.Depth == 4 & o.ApprovalStatus == "审核中");
            var jihua2 = repository.GetAllList(o => o.Depth == 5 & o.ApprovalStatus == "审核中");
            var jihua3 = repository.GetAllList(o => o.Depth == 6 & o.ApprovalStatus == "审核中");
            var lists = repository.GetAllList();

            var _lists = Mapper.Map< List < ShenHeBiao >>(lists);
            


            //一级计划

            var bumen = new List<ShenHeBiao>();
            var rs1 = new List<ShenHeOutput>();
            //遍历每个t4
            for(int i=0;i<jihua1.Count;i++)
            {
                //取当前节点信息
                rs1.Add(new ShenHeOutput
                {
                    ID = jihua1[i].ID,
                    JiHuaTargetName1 = jihua1[i].TargetName,
                    JiHuaResponsible1 = jihua1[i].Responsible,
                    JiHuaStartingTime1 = jihua1[i].StartingTime,
                    JiHuaPlannedCompletionTime1 = jihua1[i].PlannedCompletionTime,
                    Statistician= jihua1[i].Statistician,
                    CompletionCriteria= jihua1[i].CompletionCriteria,
                    AccountingMethod= jihua1[i].AccountingMethod,
                    ResourceSupport= jihua1[i].ResourceSupport,
                    Department = jihua1[i].Department,

                });

                //找他的父级
                var p = _lists.Where(o => o.ID == jihua1[i].ParentTargetID).ToList().First();
                //部门目标集合
                bumen.Add(p);
            }

            //战略目标
            var zhanlue = new List<ShenHeBiao>();

            //遍历每个部门目标
            for(int i=0;i<rs1.Count;i++)
            {
                //取当前节点信息
                rs1[i].BuMenTargetName = bumen[i].TargetName;

                //找他的父级
                var p = _lists.Where(o => o.ID == bumen[i].ParentTargetID).ToList().First();

                zhanlue.Add(p);

            }

            //分类
            var fenlei = new List<ShenHeBiao>();
            //遍历每个战略目标
            for (int i = 0; i < rs1.Count; i++)
            {
                //取当前节点信息
                rs1[i].ZhanLueTargetName = zhanlue[i].TargetName;

                //找他的父级
                var p = _lists.Where(o => o.ID == zhanlue[i].ParentTargetID).ToList().First();

                fenlei.Add(p);

            }

            var gen = new List<ShenHeBiao>();
            //遍历每个分类目标
            for (int i = 0; i < rs1.Count; i++)
            {
                //取当前节点信息
                rs1[i].FenLeiTargetName = fenlei[i].TargetName;
                

                //找他的父级
                var p = _lists.Where(o => o.ID == fenlei[i].ParentTargetID).ToList().First();

                gen.Add(p);

            }


            //二级计划
            var jihua2_1 = new List<ShenHeBiao>();
            var rs2 = new List<ShenHeOutput>();
            //遍历每个二级计划
            for (int i = 0; i < jihua2.Count; i++)
            {
                //取当前节点信息
                rs2.Add(new ShenHeOutput
                {
                    ID = jihua2[i].ID,
                    JiHuaTargetName2 = jihua2[i].TargetName,
                    JiHuaResponsible2 = jihua2[i].Responsible,
                    JiHuaStartingTime2 = jihua2[i].StartingTime,
                    JiHuaPlannedCompletionTime2 = jihua2[i].PlannedCompletionTime,
                    Statistician = jihua2[i].Statistician,
                    CompletionCriteria = jihua2[i].CompletionCriteria,
                    AccountingMethod = jihua2[i].AccountingMethod,
                    ResourceSupport = jihua2[i].ResourceSupport,
                    Department = jihua2[i].Department,
                });
                //找他的一级计划
                var p = _lists.Where(o => o.ID == jihua2[i].ParentTargetID).ToList().First();
                //部门目标集合
                jihua2_1.Add(p);
            }

            //一级计划

            var bumen2_1 = new List<ShenHeBiao>();
            //遍历每个一级计划
            for (int i = 0; i < rs2.Count; i++)
            {
                //取当前节点信息

                rs2[i].JiHuaTargetName1 = jihua2_1[i].TargetName;
                rs2[i].JiHuaResponsible1 = jihua2_1[i].Responsible;
                rs2[i].JiHuaStartingTime1 = jihua2_1[i].StartingTime;
                rs2[i].JiHuaPlannedCompletionTime1 = jihua2_1[i].PlannedCompletionTime;

                //找他的父级
                var p = _lists.Where(o => o.ID == jihua2_1[i].ParentTargetID).ToList().First();
                //部门目标集合
                bumen2_1.Add(p);
            }

            //战略目标
            var zhanlue2_1 = new List<ShenHeBiao>();

            //遍历每个部门目标
            for (int i = 0; i < rs2.Count; i++)
            {
                //取当前节点信息
                rs2[i].BuMenTargetName = bumen2_1[i].TargetName;

                //找他的父级
                var p = _lists.Where(o => o.ID == bumen2_1[i].ParentTargetID).ToList().First();

                zhanlue2_1.Add(p);

            }

            //分类
            var fenlei2_1 = new List<ShenHeBiao>();
            //遍历每个战略目标
            for (int i = 0; i < rs2.Count; i++)
            {
                //取当前节点信息
                rs2[i].ZhanLueTargetName = zhanlue2_1[i].TargetName;

                //找他的父级
                var p = _lists.Where(o => o.ID == zhanlue2_1[i].ParentTargetID).ToList().First();

                fenlei2_1.Add(p);

            }

            var gen2_1 = new List<ShenHeBiao>();
            //遍历每个分类目标
            for (int i = 0; i < rs2.Count; i++)
            {
                //取当前节点信息
                rs2[i].FenLeiTargetName = fenlei2_1[i].TargetName;

                //找他的父级
                var p = _lists.Where(o => o.ID == fenlei2_1[i].ParentTargetID).ToList().First();

                gen2_1.Add(p);

            }



            //三级计划
            var jihua3_3 = new List<ShenHeBiao>();
            var rs3 = new List<ShenHeOutput>();
            //遍历每个三级计划
            for (int i = 0; i < jihua3.Count; i++)
            {
                //取当前节点信息
                rs3.Add(new ShenHeOutput
                {
                    ID = jihua3[i].ID,
                    JiHuaTargetName3 = jihua3[i].TargetName,
                    JiHuaResponsible3 = jihua3[i].Responsible,
                    JiHuaStartingTime3 = jihua3[i].StartingTime,
                    JiHuaPlannedCompletionTime3 = jihua3[i].PlannedCompletionTime,
                    Statistician = jihua3[i].Statistician,
                    CompletionCriteria = jihua3[i].CompletionCriteria,
                    AccountingMethod = jihua3[i].AccountingMethod,
                    ResourceSupport = jihua3[i].ResourceSupport,
                    Department = jihua3[i].Department,
            });
                //找他的一级计划
                var p = _lists.Where(o => o.ID == jihua3[i].ParentTargetID).ToList().First();
                //部门目标集合
                jihua3_3.Add(p);
            }


            //二级计划
            var jihua3_2 = new List<ShenHeBiao>();
            //遍历每个二级计划
            for (int i = 0; i < rs3.Count; i++)
            {
                //取当前节点信息
                rs3[i].JiHuaTargetName2 = jihua3_3[i].TargetName;
                rs3[i].JiHuaResponsible2 = jihua3_3[i].Responsible;
                rs3[i].JiHuaStartingTime2 = jihua3_3[i].StartingTime;
                rs3[i].JiHuaPlannedCompletionTime2 = jihua3_3[i].PlannedCompletionTime;

                //找他的一级计划
                var p = _lists.Where(o => o.ID == jihua3_3[i].ParentTargetID).ToList().First();
                //部门目标集合
                jihua3_2.Add(p);
            }

            //一级计划

            var bumen3_1 = new List<ShenHeBiao>();
            //遍历每个一级计划
            for (int i = 0; i < rs3.Count; i++)
            {
                //取当前节点信息

                rs3[i].JiHuaTargetName1 = jihua3_2[i].TargetName;
                rs3[i].JiHuaResponsible1 = jihua3_2[i].Responsible;
                rs3[i].JiHuaStartingTime1 = jihua3_2[i].StartingTime;
                rs3[i].JiHuaPlannedCompletionTime1 = jihua3_2[i].PlannedCompletionTime;

                //找他的父级
                var p = _lists.Where(o => o.ID == jihua3_2[i].ParentTargetID).ToList().First();
                //部门目标集合
                bumen3_1.Add(p);
            }

            //战略目标
            var zhanlue3_1 = new List<ShenHeBiao>();

            //遍历每个部门目标
            for (int i = 0; i < rs3.Count; i++)
            {
                //取当前节点信息
                rs3[i].BuMenTargetName = bumen3_1[i].TargetName;

                //找他的父级
                var p = _lists.Where(o => o.ID == bumen3_1[i].ParentTargetID).ToList().First();

                zhanlue3_1.Add(p);

            }

            //分类
            var fenlei3_1 = new List<ShenHeBiao>();
            //遍历每个战略目标
            for (int i = 0; i < rs3.Count; i++)
            {
                //取当前节点信息
                rs3[i].ZhanLueTargetName = zhanlue3_1[i].TargetName;

                //找他的父级
                var p = _lists.Where(o => o.ID == zhanlue3_1[i].ParentTargetID).ToList().First();

                fenlei3_1.Add(p);

            }

            var gen3_1 = new List<ShenHeBiao>();
            //遍历每个分类目标
            for (int i = 0; i < rs3.Count; i++)
            {
                //取当前节点信息
                rs3[i].FenLeiTargetName = fenlei3_1[i].TargetName;

                //找他的父级
                var p = _lists.Where(o => o.ID == fenlei3_1[i].ParentTargetID).ToList().First();

                gen3_1.Add(p);

            }





            var rs = new List<ShenHeOutput>();



            rs=(rs1);
            rs.AddRange(rs2);
            rs.AddRange(rs3);



            result.datas = rs;



            result.status = 200;
            return result;

        }

        public ResultDto<List<ShenHeOutput>> ChaXunShenHeDepartment(string department)
        {
            var result = new ResultDto<List<ShenHeOutput>>();
            var t = ChaXunShenHeTemp().datas.Where(d=>d.Department== department).ToList();
            result.datas = t;
            return result;
        }

        public ResultDto<List<ShenHeOutput>> ChaXunShenHe()
        {
            var result = new ResultDto<List<ShenHeOutput>>();

            //查询计划  深度>=4 审核中
            var t = repository.GetAllList(o => o.Depth >= 4 & o.ApprovalStatus == "审核中");
            var t1 = repository.GetAllList();
            var datas = Mapper.Map<List<ShenHeBiao>>(t1);
            t.Count();
            t1.Count();
            var lists = Mapper.Map<List<ShenHeBiao>>(t);
            var inputs = new List<ShenHeBiao>();

            foreach (var i in lists)
            {
                var input = new ShenHeBiao();
                input = GetTargets(datas, i);
                inputs.Add(input);
            
           
            }

            var outputs = new List<ShenHeOutput>();
            //遍历集合，按深度从每个节点取值
            foreach (var j in inputs)
            {
                var output = new ShenHeOutput();
                var res = GetShenHe(j, output);
                res.ID = j.ID;
                outputs.Add(res);
            }

            result.datas = outputs;
            result.status = 200;
            return result;
        }

        // 遍历每个节点取值
        private ShenHeOutput GetShenHe(ShenHeBiao shenHe,  ShenHeOutput t)
        {
            var newt = new ShenHeOutput();

            if (shenHe == null)
            {
                return t;
            }
            if (shenHe.Depth == 1)
            {
                //取分类
                t.FenLeiTargetName = shenHe.TargetName;
            }
            if (shenHe.Depth == 2)
            {
                //取战略目标
                t.ZhanLueTargetName = shenHe.TargetName;
            }
            if (shenHe.Depth == 3)
            {
                //取部门目标
                t.BuMenTargetName = shenHe.TargetName;
            }
            if (shenHe.Depth == 4)
            {
                //取计划1
                t.JiHuaTargetName1 = shenHe.TargetName;
                t.JiHuaResponsible1 = shenHe.Responsible;
                t.JiHuaStartingTime1 = shenHe.StartingTime;
                t.JiHuaPlannedCompletionTime1 = shenHe.PlannedCompletionTime;
            }
            if (shenHe.Depth == 5)
            {
                //计划2
                t.JiHuaTargetName2 = shenHe.TargetName;
                t.JiHuaResponsible2 = shenHe.Responsible;
                t.JiHuaStartingTime2 = shenHe.StartingTime;
                t.JiHuaPlannedCompletionTime2 = shenHe.PlannedCompletionTime;
            }
            if (shenHe.Depth == 6)
            {
                //计划3
                t.JiHuaTargetName3 = shenHe.TargetName;
                t.JiHuaResponsible3 = shenHe.Responsible;
                t.JiHuaStartingTime3 = shenHe.StartingTime;
                t.JiHuaPlannedCompletionTime3 = shenHe.PlannedCompletionTime;
            }
            
            newt = GetShenHe(shenHe.Child, t);
            return newt;
        }

        //向上查当前节点的一条路径
        //给我一个ID
        private ShenHeBiao GetTargets(List<ShenHeBiao> datas, ShenHeBiao nodes)
        {
            var result = new ShenHeBiao();

            if (nodes.ParentTargetID == -1)
                return nodes;
            //父节点
            var lists = datas.Where(u => u.ID == nodes.ParentTargetID).ToList().First();

            //加入子节点
            lists.Child = nodes;
            result = GetTargets(datas, lists);

            return result;
        }

        public ResultDto<bool> BuMenPiLiangInsert(BuMenInput2 input)
        {
            var result = new ResultDto<bool>();

            foreach (var i in input.Departments)
            {
                try
                {
                    var model = Mapper.Map<Targets>(input);
                    var pdepth = repository.Get(input.ParentTargetID).Depth;
                    model.Depth = pdepth + 1;
                    model.Department = i;
                    repository.Insert(model);
                    result.status = 200;
                    result.datas = true;
                }
                catch (Exception ex)
                {
                    result.message = ex.Message;
                    result.status = 500;
                    result.datas = false;
                }

            }

            return result;
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            dbContext.Dispose();
        }

    }
}
